
export function getBase64Image(img) {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
     // 可选其他值 image/jpeg
    return canvas.toDataURL("image/png");
}
export function main(src, cb) {
    const image = new Image();
    image.src = src;
    image.crossOrigin = "*"; // 支持跨域图片
    image.onload = function(){
        const base64 = getBase64Image(image);
        cb && cb(base64);
    }
}
/**
 * 特殊转义字符替换成回车符
 * @param value
 * @returns {*}
 */
export function filterRuturn(value) {
    return value.replace(/(\r\n)|(\\n)/g , '\n')
}

/**
 * 格式限制200k JPG/PNG 格式
 * @param file
 * @param size
 * @returns {{text: string, status: boolean}}
 */
export function uploadLimit(file, size) {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLt = file.size / size / 1024 < 1;
    let text = '';
    if (!isJPG && !isPNG) {
        text = '上传头像图片只能是 JPG/PNG 格式!'
    }
    if (!isLt) {
        text = `上传头像图片大小不能超过 ${size} KB!`
    }
    return {
        status: isJPG && isLt || isPNG && isLt,
        text: text
    };
}

/**
 * 生成formData对象
 * @param file 文件对象
 * @param pic_folder 文件存放文件夹名
 */
export function getFormData(file, pic_folder) {
    let formData = new FormData();
    formData.append('file', file);
    formData.append('method', 'uploadImage');
    formData.append('pic_folder', pic_folder);
    return formData
}

/**
 * 时间标准格式转化年月日时分秒
 * @param datatime 时间标准格式
 */
export function getDatatime(datatime) {
    let year = datatime.getFullYear()
    let month = datatime.getMonth() + 1 < 10 ? '0' + (datatime.getMonth() + 1) : datatime.getMonth() + 1
    let day = datatime.getDate() < 10 ? '0' + datatime.getDate() : datatime.getDate()
    let hour = datatime.getHours() < 10 ? '0' + datatime.getHours() :datatime.getHours()
    let minute = datatime.getMinutes() < 10 ? '0' + datatime.getMinutes() : datatime.getMinutes()
    let second = datatime.getSeconds() <10 ? '0' + datatime.getSeconds() :  datatime.getSeconds()
    return year + '-' + month + '-' + day + ' '+ hour + ':' + minute + ':' + second
}